<template>
  <view class="p-[40rpx] box-border text-center">
    <view class="mb-[30rpx] flex flex-center">
      <image src="@/assets/img/xyi.svg" mode="widthFix" class="w-[120rpx] h-[120rpx]" />
    </view>
    <text class="text-[48rpx] mb-[30rpx] block text-[#4caf50] font-bold">签署电子协议</text>
    <text class="text-[30rpx] text-[#999] leading-[1.6] mb-[60rpx] block">
      根据国家卫生健康委员会要求，申请{{ isHuaSheng ? '电子健康码' : '诊疗卡' }}需要签署《{{ isHuaSheng ? '电子健康码' : '诊疗卡' }}使用协议》，请仔细阅读协议内容后签署。
    </text>

    <nut-form
      ref="formRef"
      :model-value="formData"
      :rules="{
        name: [
          { required: true, message: '请填写姓名' },
          { validator: nameValidator, message: '姓名长度在2-20个字符之间' }
        ],
        phone: [
          { required: true, message: '请填写手机号' },
          { validator: phoneValidator, message: '请输入正确的手机号' }
        ],
        idCard: [
          { required: true, message: '请填写身份证号' },
          { validator: idCardValidator, message: '请输入正确的身份证号' }
        ]
      }"
    >
      <!-- 姓名输入 -->
      <nut-form-item label="姓名" prop="name" class="mb-[20rpx]">
        <nut-input 
          v-model="formData.name" 
          placeholder="请输入真实姓名"
          class="text-[32rpx]"
        />
      </nut-form-item>
      
      <!-- 手机号输入 -->
      <nut-form-item label="手机号" prop="phone" class="mb-[20rpx]">
        <nut-input 
          v-model="formData.phone" 
          placeholder="请输入手机号码"
          class="text-[32rpx]"
          type="number"
          maxlength="11"
        />
      </nut-form-item>
      
      <!-- 身份证号输入 -->
      <nut-form-item label="身份证号" prop="idCard" class="mb-[20rpx]">
        <nut-input 
          v-model="formData.idCard" 
          placeholder="请输入身份证号码"
          class="text-[32rpx]"
          maxlength="18"
        />
      </nut-form-item>
    </nut-form>

    <view class="bg-[#f8f9fa] rounded-[24rpx] p-[50rpx] text-center mb-[40rpx] border border-[#e9ecef]">
      <text>合同名称：{{ contractName }}</text>
    </view>

    <nut-button type="primary" size="large"
      class="h-[88rpx] text-[36rpx] bg-gradient-to-r from-[#4caf50] to-[#2e7d32]" @click="onSign">
      <template #icon>
        <IconFont name="edit" class="mr-[10rpx]" />
      </template>
      <text>去签署</text>
    </nut-button>
  </view>
</template>

<script setup lang="ts">
import { IconFont } from '@nutui/icons-vue-taro'
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { useAuthStore } from '@/store'
import { storeToRefs } from 'pinia'
import { edit } from '@/service/api/nurse_nurses'
import { useGetAuthInfo } from '@/hooks'
import { request } from '@/service/request'
import { localStg } from '@/utils'

const props = defineProps<{
  contractName: string,
  isHuaSheng: boolean
}>()

const emit = defineEmits(['sign'])

// 获取用户store
const authStore = useAuthStore()
const { nurseUser } = storeToRefs(authStore)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  idCard: '',
  phone: ''
})

// 验证函数
const nameValidator = (val: string) => {
  if (val.length >= 2 && val.length <= 20) {
    return Promise.resolve()
  } else {
    return Promise.reject('姓名长度在2-20个字符之间')
  }
}

const phoneValidator = (val: string) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (phoneReg.test(val)) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入正确的手机号')
  }
}

const idCardValidator = (val: string) => {
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (idCardReg.test(val)) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入正确的身份证号')
  }
}

// 初始化表单数据
const initFormData = () => {
  if (nurseUser.value) {
    formData.name = nurseUser.value.name || (localStg.get('name') || '')
    formData.idCard = nurseUser.value.idcard || (localStg.get('idcard') || '')
    formData.phone = nurseUser.value.phone || (localStg.get('phone') || '')
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initFormData()
})

// 签署按钮点击事件
async function onSign() {
  try {
    // 表单验证
    const { valid, errors } = await formRef.value?.validate()
    
    if (valid) {
      // 发送表单数据到父组件
      emit('sign', {
        name: formData.name,
        idcard: formData.idCard,
        phone: formData.phone
      })
      const data = { 
        id: nurseUser.value.id,
        name: formData.name,
        idcard: formData.idCard,
        phone: formData.phone
      };

      localStg.set('name', formData.name)
      localStg.set('idcard', formData.idCard)
      localStg.set('phone', formData.phone)

      const res = await request.put('/nurse_user/nurseUser/edit', data, {
          useErrMsg: true
      });
      // res
      //重新请求用户数据
      useGetAuthInfo()
    } else {
      // 表单验证失败
      Taro.showToast({
        title: '请完善表单信息',
        icon: 'none'
      })
    }
  } catch (error) {
    // 表单验证失败
    Taro.showToast({
      title: '请完善表单信息',
      icon: 'none'
    })
  }
}
</script> 